package com.itheima.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.Employee;
import com.itheima.pojo.Pageparam;
import com.itheima.result.R;
import com.itheima.service.IEmployeeService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;

/**
 * <p>
 * 员工信息 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-11-28
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService sc;
    long id=Thread.currentThread().getId();
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session) {
        log.info("控制层线程id为 {}",id);
        String username = employee.getUsername();
        Employee emp = sc.findEmployee(username);
        R r = null;
        if (null != emp) {
            String password = employee.getPassword();
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            if (password.equals(emp.getPassword())) {
                emp.setPassword(null);
                r = R.success(emp);
            } else {
                r = R.error("密码输入错误");
            }
            if (emp.getStatus() == 0) {
                r.setCode(0);
                r.setMsg(r.getMsg() + "  账号已禁用");
            }
        } else {
            r = R.error("登录失败！");
        }
        if (r.getCode() == 1) {
            session.setAttribute("employee", emp);
        }
        return r;
    }

    @PostMapping("/logout")
    public R logout(HttpSession session) {
        try {
            session.invalidate();
            return R.success(null);
        } catch (Exception e) {
            return R.error("退出失败");
        }


    }

    @GetMapping("/page/{param}")
    public R initPage(@PathVariable String param) {
        System.out.println(param);
        Pageparam pageparam = JSON.parseObject(param, Pageparam.class);
        Page pageResult = sc.initPage(pageparam);
        return R.success(pageResult);

    }

    @PostMapping
    public R<String> addEmp(@RequestBody Employee employee) {
        int row = sc.addEmp(employee);
        R r = null;
        if (row > 0) {
            r = R.success("添加成功");
        } else {
            r = R.error("添加失败");

        }
        return r;
    }
    @PutMapping
    public R<String> updateEmp(@RequestBody Employee employee) {
        int row = sc.updateEmp(employee);
        R r = null;
        if (row > 0) {
            r = R.success("修改成功");
        } else {
            r = R.error("修改失败");

        }
        return r;
    }

}

